﻿using Aliyun.OSS;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Media.Animation;
using static EzyConfigurator.Data;

namespace EzyConfigurator
{
    /// <summary>
    /// RegisterCMDUserWindow.xaml 的交互逻辑
    /// </summary>
    public partial class RegisterCMDUserWindow : Window
    {
        public RegisterCMDUserWindow()
        {
            InitializeComponent();
        }
        string m_userName;
        string m_password;
        string loginUri = "http://note.func.zykj.org/api/Account/GuestLogin";
        string getOssTokenUri = "http://note.func.zykj.org/api/Account/GetOssToken";
        string AddNoteUrl = "http://note.func.zykj.org/api/Notes/AddOrUpdate";
        private HttpClient httpClient = new HttpClient();

        private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            m_userName = AccountTextBox.Text;
            m_password = PasswordTextBox.Password;
            BeginStoryboard(Resources["ShowLoading"] as Storyboard);
            Thread registerThread = new Thread(RegisterTask);
            registerThread.TrySetApartmentState(ApartmentState.STA);
            registerThread.Start();
        }

        private void RegisterTask()
        {
            try
            {
                LoginData loginData = new LoginData()
                {
                    userName = m_userName,
                    password = m_password
                };
                string requestData = AES.AesEncrypt(JsonConvert.SerializeObject(loginData));
                HttpContent content = new StringContent(requestData);
                content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                var response = httpClient.PostAsync(loginUri, content).Result.Content.ReadAsStringAsync().Result;
                CommonReturnData returnData = JsonConvert.DeserializeObject<CommonReturnData>(response);
                if (returnData.msg == "操作成功")
                {
                    UserInfo userInfo = JsonConvert.DeserializeObject<UserInfo>(AES.AesDecrypt(returnData.data));
                    httpClient.DefaultRequestHeaders.Clear();
                    httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {userInfo.token}");
                    string ossResult = httpClient.GetAsync(getOssTokenUri).Result.Content.ReadAsStringAsync().Result;
                    CommonReturnData ossReturnData = JsonConvert.DeserializeObject<CommonReturnData>(ossResult);

                    if (ossReturnData.msg == "操作成功")
                    {
                        string ossAccessDataJson = AES.AesDecrypt(ossReturnData.data);
                        OssAccessReturnData ossAccessData = JsonConvert.DeserializeObject<OssAccessReturnData>(ossAccessDataJson);
                        userInfo.accessKeyId = ossAccessData.accessKeyId;
                        userInfo.accessKeySecret = ossAccessData.accessKeySecret;
                        userInfo.securityToken = ossAccessData.securityToken;
                        /*
                        Clipboard.SetDataObject(userInfo.accessKeyId);
                        MessageBox.Show("");
                        Clipboard.SetDataObject(userInfo.accessKeySecret);
                        MessageBox.Show("");
                        Clipboard.SetText(userInfo.securityToken);
                        MessageBox.Show(ossAccessDataJson);*/
                        var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
                        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
                        var accessKeyId = userInfo.accessKeyId;
                        var accessKeySecret = userInfo.accessKeySecret;
                        var stsToken = userInfo.securityToken;
                        // 填写Bucket名称，例如examplebucket。
                        var bucketName = "friday-note";
                        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
                        var objectName = $"cloudnote/notes/sxz/{userInfo.userId}/CommandInput.txt";
                        // 填写字符串。
                        var objectContent = "";

                        // 创建OssClient实例。
                        var client = new OssClient(endpoint, accessKeyId, accessKeySecret, stsToken);

                        byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
                        MemoryStream requestContent = new MemoryStream(binaryData);
                        // 上传文件。
                        client.PutObject(bucketName, objectName, requestContent);
                        Console.WriteLine("Put object succeeded");


                        httpClient.DefaultRequestHeaders.Clear();
                        httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {userInfo.token}");
                        AddFileData addFileData = new AddFileData()
                        {
                            fileName = "CommandInput.txt",
                            fileId = Guid.NewGuid().ToString("N"),
                            fileUrl = $"cloudnote/notes/sxz/{userInfo.userId}/CommandInput.txt",
                            parentId = "0",
                            type = 6
                        };
                        string addNoteRequestData = JsonConvert.SerializeObject(addFileData);
                        HttpContent addNoteRequestContent = new StringContent(AES.AesEncrypt(addNoteRequestData));
                        addNoteRequestContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
                        var resp = httpClient.PostAsync(AddNoteUrl, addNoteRequestContent).Result.Content.ReadAsStringAsync().Result;
                        
                        if(JsonConvert.DeserializeObject<CommonReturnData>(resp).msg!="操作成功")
                            throw new Exception(JsonConvert.DeserializeObject<CommonReturnData>(resp).msg);
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            StatusLabel.Text = "操作成功";
                        });

                    }
                    else
                    {
                        throw new Exception(ossReturnData.msg);
                    }
                }
                else
                {
                    throw new Exception(returnData.msg);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Application.Current.Dispatcher.Invoke(() =>
                {
                    StatusLabel.Text = "操作出错";
                });
            }
            finally
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    BeginStoryboard(Resources["CloseLoading"] as Storyboard);
                });
            }
        }

    }
}
